package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.form.FormRequest;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.FormLoginDto;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.CopyMap;
import cc.linker.steplink.crm.merchant.dao.*;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantInfoDao;
import cc.linker.steplink.crm.merchant.pojo.*;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.ZsGoodsDao;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.response.ResponseException;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ShopGoodsService {

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private ShopGroupDao shopGroupDao;
    @Autowired
    private HttpService httpService;
    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private SmsService smsService;
    @Autowired
    private MerchantInfoDao merchantInfoDao;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Autowired
    private ZsGoodsDao zsGoodsDao;
    @Autowired
    private WxDao wxDao;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MallService mallService;
    @Autowired
    private EnrollDao enrollDao;
    @Autowired
    private FormRequest formRequest;
    @Autowired
    private CommonsService commonsService;
    @Autowired
    private DataSourceTransactionManager txManager;
    @Autowired
    private IsLossGoodsService isLossGoodsService;
    @Autowired
    private NewMallService newMallService;

    public BasePageDto<ShopGoods> list(Map<String, Object> params) {
        BasePageDto<ShopGoods> dto = new BasePageDto<>();
        Integer perPage = (Integer) params.get("perPage");
        Integer currentPage = (Integer) params.get("currentPage");
        Integer total = shopGoodsMapper.getGoodsCount(params);
        List<ShopGoods> goodsList = null;
        if (total > 0) {
            goodsList = shopGoodsMapper.getGoodsList(params);
        }
        dto.setCon(goodsList);
        dto.setCurrentPage(currentPage);
        dto.setCount(total);
        dto.setPerPage(perPage);
        dto.setTotalPage((total % perPage == 0) ? (total / perPage) : (total / perPage + 1));
        return dto;
    }

    public void updateGoods(Map map) {
        shopGoodsMapper.updateGoods(map);
    }

    public void insertGoods(Map map) {
        shopGoodsMapper.insertGoods(map);
    }

    public void insertGoodsSpec(GoodsSpec goodsSpec) {
        shopGoodsMapper.insertGoodsSpec(goodsSpec);
    }

    public void insertSku(Sku sku) {
        shopGoodsMapper.insertSku(sku);
    }

    public void deleteGoodsSpecs(Long goodsId) {
        shopGoodsMapper.deleteGoodsSpecs(goodsId);
    }

    public void deleteSkus(Long goodsId) {
        shopGoodsMapper.deleteSkus(goodsId);
    }

    public void delete(Long[] goodsIds, String adminId, String orgId, Integer mine, Boolean ifSales) throws GlobalException {
        if (goodsIds.length == 0) {
            throw GlobalException.build("商品id不能为空");
        }
        for (Long goodsId : goodsIds) {
            newMallDao.delSecKill(goodsId);
            mallService.flushCartGoodsSkuInfo(goodsId);
        }
        if (mine == 1) {
            for (Long goodsId : goodsIds) {
                // 大麦 判断联盟商品 只移除关系
                shopGoodsMapper.deleteOrgGoods(goodsId.toString());
            }
        } else if (mine == 0 || mine == 2) {
            for (Long gid:goodsIds){
                ShopGoods goods = shopGoodsMapper.getGoods(gid);
                dynamicService.recording(adminId, orgId, 2,"删除"+goods.getGoodsName());
            }
            shopGoodsMapper.delete(goodsIds);
            shopGroupDao.delRelationByGoodsIds(goodsIds);
            shopGoodsMapper.cleanGoodsBindArticleByGoodsIds(goodsIds);
            // 删除商品时 判断设置赠品活动中的商品状态为异常
            shopGoodsMapper.updateExercise(goodsIds);
            // 删除商品 判断设置的会员卡中的商品状态为异常
            shopGoodsMapper.updateVip(goodsIds);
        }
        //删除商品 积分商品异常
        shopGoodsMapper.updateIntegralGoods(goodsIds);
//        else if (mine == 2) {
//            Map<String, Object> map = new HashMap<>();
//            // 目前只是一个个删除
//            map.put("goodsId", goodsIds[0]);
//            map.put("adminId", adminId);
//            if (ifSales) {
//                String customerId = newMallDao.getCustomerIdByUserId(map);
//                map.put("orgId", customerId);
//            } else {
//                map.put("orgId", orgId);
//            }
//            shopGoodsMapper.deleteAssociationByGoodsIdAndOrgId(map);
//        }
    }

    public void updateStatus(Map<String, Object> params) {
        shopGoodsMapper.updateStatus(params);
    }

    public void saveSpecKey(SpecKey specKey) {
        shopGoodsMapper.saveSpecKey(specKey);
    }

    public Long getSpecKeyId(SpecKey specKey) {
        return shopGoodsMapper.getSpecKeyId(specKey);
    }

    public void saveSpecValue(SpecValue specValue) {
        shopGoodsMapper.saveSpecValue(specValue);
    }

    public Long getSpecValueId(SpecValue specValue) {
        return shopGoodsMapper.getSpecValueId(specValue);
    }


    public List<SpecKey> specKeyList(Map<String, Object> params) {
        return shopGoodsMapper.specKeyList(params);
    }

    public List<SpecValue> specValueList(Long specKeyId) throws GlobalException {
        if (specKeyId == null) {
            throw new GlobalException(new ResponseException(400, "规格id不能为空"));
        }
        return shopGoodsMapper.specValueList(specKeyId);
    }

    public ShopGoods getGoods(Long goodsId) throws GlobalException {
        if (goodsId == null) {
            throw GlobalException.build("商品id不能为空");
        }
        ShopGoods shopGoods = shopGoodsMapper.getGoods(goodsId);
        List<GoodsSpec> goodsSpec = shopGoodsMapper.getSpecByGoodsId(goodsId);
        shopGoods.setGoodsSpec(goodsSpec);
        List<Sku> sku = shopGoodsMapper.getSkuByGoodsId(goodsId);
        shopGoods.setSku(sku);
        List<Map<String, Object>> labels = shopGoodsMapper.getGoodsLabelsById(goodsId);
        shopGoods.setLabels(labels);
        // 如果启用了运费模板 设置运费值为模板运费最低值
        if((null==shopGoods.getIsFreeFreight() || 0==shopGoods.getIsFreeFreight()) && !StringUtils.isEmpty(shopGoods.getFreightTemplateId())){
            shopGoods.setGoodsFreight(Double.valueOf(maiBaoLaDao.getLeastTemplateFee(shopGoods.getFreightTemplateId())));
            shopGoods.setFreightTemplateName(maiBaoLaDao.getFreightTemplateNameById(shopGoods.getFreightTemplateId()));
        }
        String serviceIds = shopGoodsMapper.getServiceIdsByGoodsId(goodsId);
        shopGoods.setServiceIds(serviceIds);
        Map<String, Object> secKill = shopGoodsMapper.getSecKill(goodsId);
        if(secKill!=null){
            shopGoods.setSecKillStartTime(secKill.get("secKillStartTime").toString());
            shopGoods.setSecKillEndTime(secKill.get("secKillEndTime").toString());
            if(secKill.get("vipLimitStart") != null){
                shopGoods.setVipLimitStart(Integer.parseInt(secKill.get("vipLimitStart").toString()));
            }
            if(secKill.get("vipLimitEnd") != null){
                shopGoods.setVipLimitEnd(Integer.parseInt(secKill.get("vipLimitEnd").toString()));
            }
            if(secKill.get("vipIds") != null){
                shopGoods.setVipIds(secKill.get("vipIds").toString());
            }
            if(secKill.get("seckillMultiole") != null){
                shopGoods.setSeckillMultiole(Double.valueOf(secKill.get("seckillMultiole").toString()));
            }
        }
        return shopGoods;
    }

    public void updateGoodsBindArticle(Map<String, Object> params) {
        shopGoodsMapper.updateGoodsBindArticle(params);
    }

    public void cleanGoodsBindArticle(Map<String, Object> params) {
        shopGoodsMapper.cleanGoodsBindArticle(params);
    }

    public void banned(Map<String, Object> params) {
        String orgId = (String) params.get("orgId");
        Long goodsId = Long.valueOf(params.get("goodsId").toString());
        ShopGoods goods = shopGoodsMapper.getGoods(goodsId);
        if (goods == null) {
            throw GlobalException.build("商品不存在");
        }
        String goodsName = goods.getGoodsName();
        String belongId = goods.getBelongId();
        String banned = goods.getBanned();
        // true=解除 false=封禁
        boolean flag = "1".equals(banned);
        params.put("banned", flag ? "0" : "1");
        String phone = shopGoodsMapper.getPhoneFromSalerByCustomerId(belongId);
        if (StringUtils.isEmpty(phone)) {
            LOGGER.warn("用户手机号不存在");
        } else {
            Map<String, Object> reqMap = new HashMap<>();
            // 9004 封禁 9005 解除封禁 product 商品 name 理由
            reqMap.put("businessType", flag ? "9005" : "9004");
            reqMap.put("mobilNumber", phone);
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("name", goodsName);
            if (!flag) {
                paramMap.put("reason", params.get("reason"));
            }
            reqMap.put("params", JSON.toJSONString(paramMap));
            String s = smsService.sendMsg(orgId, reqMap);
            LOGGER.info("banned===" + s);
        }
        shopGoodsMapper.bannedGoodsByGoodsId(params);
        params.put("orgStatus", "2");
        params.put("goodsStatus", 2);
        shopGoodsMapper.updateStatus(params);
        if (goods.getGoodsType() == 4 && !flag) {
            // 专栏封禁后，关联的内容全部下架
            shopGoodsMapper.updateContentStatusByColumnGoodsId(goodsId);
            // 专栏封禁后，删除专栏和内容的关联，并修改内容的purchase when 3 then 1 when 2 then null
            shopGoodsMapper.updatePurchaseByColumnGoodsId(goodsId);
            // 删除
            shopGoodsMapper.deleteRelationColumnAndContentByColumnGoodsId(goodsId);
        }
        if (goods.getGoodsType() == 3 && !flag) {
            // 内容被封禁后，删除和专栏的关系
            shopGoodsMapper.deleteRelationColumnAndContentByContentGoodsId(goodsId);
            // 并修改内容的purchase
            shopGoodsMapper.updatePurchaseByContentGoodsId(goodsId);
        }
    }


    public PageInfo allianceMallList(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Boolean ifSales = (Boolean) params.get("ifSales");
        if (ifSales) {
            String customerId = merchantInfoDao.getCustomerIdByAdminId((String) params.get("adminId"));
            params.put("saler", customerId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> mapList = shopGoodsMapper.listAllAllianceGoods(params);

        for (Map<String, Object> map : mapList) {
            String msg = null;
            String goodsType = map.get("goodsType").toString();
            if (!"3".equals(goodsType) && !"4".equals(goodsType)) {
                map.put("msg", msg);
                continue;
            }
            Map<String, Object> status = shopGoodsMapper.getGoodsStatusByGoodsId(map);
            if (status != null) {
                String isContentFree = status.get("isContentFree").toString();
                String isColumnFree = status.get("isColumnFree").toString();
                String isBelongColunmFree = status.get("isBelongColunmFree").toString();
                if ("1".equals(isColumnFree) || "1".equals(isContentFree) || "1".equals(isBelongColunmFree)) {
                    // 当专栏为免费时，点击参与提示“免费商品无法参与”
                    // 当内容被关联了免费专栏时，点击参与提示“免费商品无法参与”
                    // 当内容被关联的专栏设置为“免费浏览”时，点击参与提示“免费商品无法参与”
                    msg = "免费商品无法参与";
                }
                if ("-1".equals(isColumnFree) && !"-1".equals(isContentFree)) {
                    // 当内容既没有被关联专栏也无法单独销售，点击参与提示“此商品无法参与”
                    Object purchase = status.get("purchase");
                    if (purchase == null || (!"1".equals(purchase.toString()) && !"3".equals(purchase.toString()))) {
                        msg = "此商品无法参与";
                    }
                }
            }
            map.put("msg", msg);
        }


        return new PageInfo<>(mapList);
    }


    public PageInfo allianceShareList(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        Boolean ifSales = (Boolean) params.get("ifSales");
        if (ifSales) {
            String customerId = merchantInfoDao.getCustomerIdByAdminId((String) params.get("adminId"));
            params.put("saler", customerId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> mapList = shopGoodsMapper.allianceShareList(params);

        for (Map<String, Object> map : mapList) {
            String msg = null;
            String goodsType = map.get("goodsType").toString();
            if (!"3".equals(goodsType) && !"4".equals(goodsType)) {
                map.put("msg", msg);
                continue;
            }
            Map<String, Object> status = shopGoodsMapper.getGoodsStatusByGoodsId(map);
            if (status != null) {
                String isContentFree = status.get("isContentFree").toString();
                String isColumnFree = status.get("isColumnFree").toString();
                String isBelongColunmFree = status.get("isBelongColunmFree").toString();
                if ("1".equals(isColumnFree) || "1".equals(isContentFree) || "1".equals(isBelongColunmFree)) {
                    // 当专栏为免费时，点击参与提示“免费商品无法参与”
                    // 当内容被关联了免费专栏时，点击参与提示“免费商品无法参与”
                    // 当内容被关联的专栏设置为“免费浏览”时，点击参与提示“免费商品无法参与”
                    msg = "免费商品无法参与";
                }
                if ("-1".equals(isColumnFree) && !"-1".equals(isContentFree)) {
                    // 当内容既没有被关联专栏也无法单独销售，点击参与提示“此商品无法参与”
                    Object purchase = status.get("purchase");
                    if (purchase == null || (!"1".equals(purchase.toString()) && !"3".equals(purchase.toString()))) {
                        msg = "此商品无法参与";
                    }
                }
            }
            map.put("msg", msg);
        }


        return new PageInfo<>(mapList);
    }

    public void addToMall(Map<String, Object> params) {

        Map<String,Object> merParam = new HashMap<>();
        merParam.put("orgId",params.get("orgId"));
        HashMap<String, Object> goodsInfo = mallDao.getGoodsInfo(Integer.valueOf(params.get("goodsId").toString()));
        if(!StringUtils.isEmpty(goodsInfo.get("belongId"))){
            merParam.put("customerId",goodsInfo.get("belongId"));
        }
        //  商家认证
        Map<String, Object> merInfo = newMallDao.getMerInfo(merParam);
        if (merInfo == null || !"2".equals(merInfo.get("checkStatus").toString())) {
            throw GlobalException.build("暂时无法添加，商家未进行认证");
        }
        shopGoodsMapper.addToMallByGoodsId(params);
    }

    public void promotion(Map<String, Object> params, PcUserInfo userInfo) {
        if (params.get("goodsId") == null) {
            throw GlobalException.build("缺少参数");
        }
        Long goodsId =Long.valueOf(params.get("goodsId").toString());
        mallService.flushCartGoodsSkuInfo(goodsId);
        String promotion = String.valueOf(params.get("promotion"));
        if ("1".equals(promotion)) {
            Boolean ifSales = userInfo.getSaler();
            if (ifSales) {
                String adminId = userInfo.getAdminId();
                String customerId = merchantInfoDao.getCustomerIdByAdminId(adminId);
                Integer integer = wxDao.countCertificationByCustomerId(customerId);
                if (integer <= 0) {
                    throw GlobalException.build("请先完成商家认证");
                }
            } else {
                String orgId = userInfo.getOrgId();
                Integer integer = wxDao.countCertificationByOrgId(orgId);
                if (integer <= 0) {
                    throw GlobalException.build("请先完成商家认证");
                }
            }
            // 判断商品是否是推广商品 佣金是否大于返润金额 提示 此商品成交后可能出现亏损，请修改
            ShopGoods goods = shopGoodsMapper.getGoods(goodsId);
            if(!StringUtils.isEmpty(goods.getMallsGoodsId())){
                String rebate = params.get("rebate").toString();
                List<Sku> sku = shopGoodsMapper.getSkuByGoodsId(goodsId);
                if(null==sku || sku.isEmpty()){
                    //佣金
                    double cost1 = goods.getMoneyAmount()-goods.getMallsAmount();
                    int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost1 = cost1fee/100.00;
                    // 返润
                    double cost2 = goods.getMoneyAmount()*(Double.valueOf(rebate))/100;
                    int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost2 = cost2fee/100.00;
                    if(cost2>cost1 || cost1<0){
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                    }
                    // 会员价 判断
                    Double memberAmount = goods.getMemberAmount();
                    if(!StringUtils.isEmpty(memberAmount) && memberAmount!=0){
                        // 会员价
                        // 会员价返润金额
                        double cost3 = memberAmount*(Double.parseDouble(rebate))/100;
                        int cost3fee = new BigDecimal(cost3*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost3 = cost3fee/100.00;
                        // 会员价返润佣金
                        double cost4 = memberAmount-goods.getMallsAmount();
                        int cost4fee = new BigDecimal(cost4*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost4 = cost4fee/100.00;
                        if(cost3>cost4 || cost4<0){
                            LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                            throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                        }
                    }
                }else{
                    for (Sku o : sku){
                        double cost1 = o.getMoneyAmount()-o.getMallsAmount();
                        int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost1 = cost1fee/100.00;
                        double cost2 = o.getMoneyAmount()*(Double.parseDouble(rebate))/100;
                        int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost2 = cost2fee/100.00;
                        if(cost2>cost1 || cost1<0){
                            LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                            throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                        }
                        // 会员价来判断是否亏损
                        Double memberAmount = o.getMemberAmount();
                        if(!StringUtils.isEmpty(o.getMemberAmount()) && memberAmount!=0){
                            // 会员价返润金额
                            double cost3 = memberAmount*(Double.parseDouble(rebate))/100;
                            int cost3fee = new BigDecimal(cost3*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                            cost3 = cost3fee/100.00;
                            // 会员价返润佣金
                            double cost4 = memberAmount-o.getMallsAmount();
                            int cost4fee = new BigDecimal(cost4*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                            cost4 = cost4fee/100.00;
                            if(cost3>cost4 || cost4<0){
                                LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                            }
                        }
                    }
                }
            }
            //
            Map<String, Object> status = shopGoodsMapper.getGoodsStatusByGoodsId(params);
            if (status != null) {
                String isContentFree = status.get("isContentFree").toString();
                String isColumnFree = status.get("isColumnFree").toString();
                String isBelongColunmFree = status.get("isBelongColunmFree").toString();
                if ("1".equals(isColumnFree) || "1".equals(isContentFree) || "1".equals(isBelongColunmFree)) {
                    // 当专栏为免费时，点击参与提示“免费商品无法参与”
                    // 当内容被关联了免费专栏时，点击参与提示“免费商品无法参与”
                    // 当内容被关联的专栏设置为“免费浏览”时，点击参与提示“免费商品无法参与”
                    throw GlobalException.build("免费商品无法参与");
                }
                if ("-1".equals(isColumnFree) && !"-1".equals(isContentFree)) {
                    // 当内容既没有被关联专栏也无法单独销售，点击参与提示“此商品无法参与”
                    Object purchase = status.get("purchase");
                    if (purchase == null || (!"1".equals(purchase.toString()) && !"3".equals(purchase.toString()))) {
                        throw GlobalException.build("此商品无法参与");
                    }
                }
            }
        }
        shopGoodsMapper.promotion(params);
        if ("0".equals(promotion)) {
            shopGoodsMapper.deleteAssociationForMyShopByGoodsId(params);
        }
    }


    public void  checkPromotion(Map<String, Object> params,ShopGoods goods)
    {
        // 判断商品是否是推广商品 佣金是否大于返润金额 提示 此商品成交后可能出现亏损，请修改
        String rebate = params.get("rebate").toString();
        List<Sku> sku = goods.getSku();
        double goodsFreight = 0;
        if(!StringUtils.isEmpty(params.get("minGoodsFreight"))
             && goods.getIsFreeFreight()!=null &&
            goods.getIsFreeFreight()==0){
             goodsFreight = Double.valueOf(params.get("minGoodsFreight").toString())*100;
        }else if(goods.getGoodsFreight()!=null &&
                goods.getIsFreeFreight()!=null &&
                goods.getIsFreeFreight()==0){
            goodsFreight =  goods.getGoodsFreight()*100;
            if(!StringUtils.isEmpty(goods.getFreightTemplateId())){
                goodsFreight = Double.valueOf(maiBaoLaDao.getLeastTemplateFee(goods.getFreightTemplateId()))*100;
            }
        }
        if(goodsFreight>0){
            int goodsFreight2 = new BigDecimal(goodsFreight).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            goodsFreight = goodsFreight2/100.00;
        }
        if(null==sku || sku.isEmpty()){
            Double mallsAmount = goods.getMallsAmount();
            if(mallsAmount==null){
                mallsAmount = 0.0;
            }
            double reduceAmount = goods.getMoneyAmount();
            if(goods.getReduceAmount()!=null){
                reduceAmount = goods.getReduceAmount();
            }
            //佣金
            double cost1 = reduceAmount-mallsAmount;
            // 返润
            double cost2 = goods.getMoneyAmount()*(Double.valueOf(rebate))/100;
            int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            cost2 = cost2fee/100.00;
            if(mallsAmount<=0){
                Double v1 = (reduceAmount+goodsFreight);
                BigDecimal b1 = new BigDecimal(Double.toString(v1));
                BigDecimal b2 = new BigDecimal(0.1);
                v1 =  b1.multiply(b2).doubleValue();
                int allFee = new BigDecimal(v1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost1 += goodsFreight-allFee/100.00;
            }
            int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            cost1 = cost1fee/100.00;
            if(cost2>cost1 || cost1<0){
                LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goods.getGoodsId());
                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
            }
            // 会员价 判断
            Double memberAmount = goods.getMemberAmount();
            Double reduceMemberAmount = memberAmount;
            if(goods.getReduceMemberAmount()!=null){
                reduceMemberAmount = goods.getReduceMemberAmount();
            }
            if(!StringUtils.isEmpty(memberAmount) && memberAmount!=0){
                // 会员价
                // 会员价返润金额
                double cost3 = memberAmount*(Double.parseDouble(rebate))/100;
                int cost3fee = new BigDecimal(cost3*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost3 = cost3fee/100.00;
                // 会员价返润佣金
                double cost4 = reduceMemberAmount-mallsAmount;
                if(mallsAmount<=0){
                    Double v1 = (reduceMemberAmount+goodsFreight);
                    BigDecimal b1 = new BigDecimal(Double.toString(v1));
                    BigDecimal b2 = new BigDecimal(0.1);
                    v1 = b1.multiply(b2).doubleValue();
                    int allFee = new BigDecimal(v1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost4 += goodsFreight-allFee/100.00;
                }
                int cost4fee = new BigDecimal(cost4*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost4 = cost4fee/100.00;
                if(cost3>cost4 || cost4<0){
//                    throw GlobalException.build("此商品会员价成交后可能出现亏损，请修改");
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goods.getGoodsId());
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
            }
        }else{
            for (Sku o : sku){
                Double mallsAmount = o.getMallsAmount();
                if(mallsAmount==null){
                    mallsAmount = 0.0;
                }
                double reduceAmount = o.getMoneyAmount();
                if(o.getReduceAmount()!=null){
                    reduceAmount = o.getReduceAmount();
                }
                double cost1 = reduceAmount-mallsAmount;
                double cost2 = o.getMoneyAmount()*(Double.parseDouble(rebate))/100;
                int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost2 = cost2fee/100.00;
                if(mallsAmount<=0){
                    Double v1 = (reduceAmount+goodsFreight);
                    BigDecimal b1 = new BigDecimal(Double.toString(v1));
                    BigDecimal b2 = new BigDecimal(0.1);
                    v1 = b1.multiply(b2).doubleValue();
                    int allFee = new BigDecimal(v1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost1 += goodsFreight-allFee/100.00;
                }
                int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost1 = cost1fee/100.00;
                if(cost2>cost1 || cost1<0){
//                    throw GlobalException.build("此商品成交后可能出现亏损，请修改");
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goods.getGoodsId());
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
                // 会员价来判断是否亏损
                Double memberAmount = o.getMemberAmount();
                Double reduceMemberAmount = memberAmount;
                if(o.getReduceMemberAmount()!=null){
                    reduceMemberAmount = o.getReduceMemberAmount();
                }
                if(!StringUtils.isEmpty(o.getMemberAmount()) && memberAmount!=0){
                    // 会员价返润金额
                    double cost3 = memberAmount*(Double.parseDouble(rebate))/100;
                    int cost3fee = new BigDecimal(cost3*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost3 = cost3fee/100.00;
                    // 会员价返润佣金
                    double cost4 = reduceMemberAmount-mallsAmount;
                    if(mallsAmount<=0){
                        Double v1 = (reduceMemberAmount+goodsFreight);
                        BigDecimal b1 = new BigDecimal(Double.toString(v1));
                        BigDecimal b2 = new BigDecimal(0.1);
                        v1 =  b1.multiply(b2).doubleValue();
                        int allFee = new BigDecimal(v1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost4 += goodsFreight-allFee/100.00;
                    }
                    int cost4fee = new BigDecimal(cost4*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost4 = cost4fee/100.00;
                    if(cost3>cost4 || cost4<0){
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goods.getGoodsId());
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
//                        throw GlobalException.build("此商品会员价成交后可能出现亏损，请修改");
                    }
                }
            }
        }
    }

    public PageInfo productPromotion(Map<String, Object> params) {
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> mapList = shopGoodsMapper.listProductPromotionByOrgId(params);
        return new PageInfo<>(mapList);
    }

    public void productShared(Map<String, Object> params) {
        this.shared(params);
        shopGoodsMapper.productShared(params);
    }

    public void productChoose(Map<String, Object> params) {
        Integer association = shopGoodsMapper.getAssociationByGoodsIdAndOrgId(params);
        if (association == 1) {
            // 已有，删除
            shopGoodsMapper.deleteAssociationByGoodsIdAndOrgId(params);
        } else {
            // 没有，关联
            shopGoodsMapper.associationGoodsAndOrg(params);
        }

    }

    public List<Map<String, Object>> orgInfoList() {
        List<Map<String, Object>> orgInfoList = shopGoodsMapper.getOrgInfoList();
        orgInfoList.forEach(x -> {
            if (x.get("orgName") == null) {
                Map<String, Object> reqMap = new HashMap<>();
                String orgId = (String) x.get("orgId");
                reqMap.put("orgcode", orgId);
                reqMap.put("action", "getOrgInfo");
                String url = systemProperties.getUserCenter() + "/WebAPI/BaseInfo.aspx";
                String result = "";
                try {
                    result = httpService.doGet(url, reqMap);
                } catch (URISyntaxException | IOException e) {
                    LOGGER.warn(orgId + "机构名称获取失败");
                }
                if (!"".equals(result)) {
                    Map parse = (Map) JSON.parse(result);
                    String orgName = (String) parse.get("OrgName");
                    if (orgName != null) {
                        x.put("orgName", orgName);
                        shopGoodsMapper.updateOrgInfo(x);
                    }
                }
            }
        });
        return orgInfoList;
    }

    public List<Map<String, Object>> getViewChoose(Map<String, Object> params) {
        return shopGoodsMapper.getViewChoose(params);
    }

    private void shared(Map<String, Object> params) {
        Integer shared = (Integer) params.get("shared");
        if (shared == null) {
            throw GlobalException.build("缺少参数");
        }
        if (shared == 0) {
            params.put("rebate", 0);
            shopGoodsMapper.deleteAssociationByGoodsIdAndOrgId(params);
        }
    }

    public void mediaProductShared(Map<String, Object> params) {
        this.shared(params);
        shopGoodsMapper.mediaProductShared(params);
    }

    public PageInfo productPromotionForSaler(Map<String, Object> params) {
        String adminId = (String) params.get("adminId");
        String customerId = merchantInfoDao.getCustomerIdByAdminId(adminId);
        params.put("customerId", customerId);
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> mapList = shopGoodsMapper.listProductPromotionByCustomerId(params);
        return new PageInfo<>(mapList);
    }

    public void mediaProductChoose(Map<String, Object> params) {
        if (!params.containsKey("goodsId")) {
            throw GlobalException.build("缺少参数");
        }
        String goodsId = (String) params.get("goodsId");
        String[] split = goodsId.split(",");
        params.put("goodsIds", split);
        shopGoodsMapper.mediaProductChoose(params);
    }

    public List<Long> getGoodsIdsByTemplateId(String templateId) {
        return shopGoodsMapper.getGoodsIdsByTemplateId(templateId);
    }

    public List<Map<String,Object>> getGoodsServiceList(Map<String, Object> param) {
        List<Map<String, Object>> goodsServiceList = shopGoodsMapper.getGoodsServiceList(param);
        if(null!=goodsServiceList && goodsServiceList.size()>0){
            for(Map<String, Object> item:goodsServiceList){
                int count = shopGoodsMapper.getGoodsServiceBusiCount(item.get("id").toString());
                item.put("isUsed",count>0);
            }
        }
        return goodsServiceList;
    }

    public void saveGoodsService(Map<String, Object> param) {
        int repeatCount = shopGoodsMapper.getGoodsNameRepeatCount(param);
        if (repeatCount > 0) {
            throw GlobalException.build("已存在名称为'" + param.get("name") + "'的服务");
        }
        if (param.containsKey("id") && !StringUtils.isEmpty(param.get("id"))) {
            //编辑
            shopGoodsMapper.updateGoodsService(param);
        } else {
            //新增
            shopGoodsMapper.addGoodsService(param);
        }
    }

    public void delGoodsService(Map<String, Object> param) {
        shopGoodsMapper.delGoodsService(param);
    }

    public List<Map<String, Object>> getAllGoodsServiceList(Map<String, Object> param) {
        List<Map<String, Object>> goodsServiceList = shopGoodsMapper.getAllGoodsServiceList(param);
        return goodsServiceList;
    }

    public Map<String, Object> getGoodsServiceInfo(Integer id) {
        return shopGoodsMapper.getGoodsServiceInfo(id);
    }

    public List<Map<String, Object>> getMyShareGoodsList(Map<String, Object> param) {
        List<Map<String, Object>> myShareGoodsList = shopGoodsMapper.getMyShareGoodsList(param);
        if(myShareGoodsList!=null && myShareGoodsList.size()>0){
            for(Map<String, Object> myShareGoods:myShareGoodsList){
                myShareGoods.put("contentType",null);
                Long goodsId = Long.parseLong(myShareGoods.get("goodsId").toString());
                String goodsType = myShareGoods.get("goodsType").toString();
                if("3".equals(goodsType)||"4".equals(goodsType)){
                    Map<String, Object> goodsContent = zsGoodsDao.getGoodsContent(goodsId);
                    if(goodsContent!=null){
                        myShareGoods.put("contentType",goodsContent.get("contentType"));
                    }
                }
//                //TODO 获取第三方销量
//                myShareGoods.put("otherSaleNum",0);
            }
        }
        return myShareGoodsList;
    }

    public void saveSharing(Map<String, Object> param) {
        if(StringUtils.isEmpty(param.get("type")) || StringUtils.isEmpty(param.get("id"))){
            throw GlobalException.build("参数错误");
        }
        String type = param.get("type").toString();
        switch (type){
            case "1":
            case "2":
                //商品
                shopGoodsMapper.saveSharing(param);
                break;
            case "3":
                //报名
                enrollDao.saveSharing(param);
                break;
            case "4":
                //表单
                param.put("formId",param.get("id"));
                formRequest.doRequest("/pc/form/templates/saveSharing", param, (FormLoginDto)param.get("formLoginDto"));
                break;
                default:break;
        }
    }

    public Map<String, Object> getImportGoods(Map goodsNew) {
       return shopGoodsMapper.getImportGoods(goodsNew);
    }

    public void exportTemplate( String fileName, List<Map<String,Object>> goodsList,HttpServletResponse response) {
        String[] title = {"商品id(必填)", "规格id(必填)", "商品名称", "规格","调整后价格(元,必填)","调整后库存(件,必填)"};
        String[] strings = {"goodsId", "skuId", "goodsName", "skuValue", "moneyAmount", "goodsCount"};
        try {
            commonsService.excelDownload(goodsList, strings, title, fileName, response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void exportTemplateError( String fileName, List<Map<String,Object>> goodsList,HttpServletResponse response) {
        String[] title = {"商品id(必填)", "规格id(必填)", "商品名称", "规格","调整后价格(元,必填)","调整后库存(件,必填)","原因"};
        String[] strings = {"goodsId", "skuId", "goodsName", "skuValue", "moneyAmount", "goodsCount","reason"};
        try {
            commonsService.excelDownload(goodsList, strings, title, fileName, response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void updateGoodsList(Map<String, Object> params,PcUserInfo userinfo) {
        if(StringUtils.isEmpty(params.get("importId")) || StringUtils.isEmpty(params.get("goodsList"))){
            throw GlobalException.build("参数错误");
        }
        String importId = params.get("importId").toString();
        List<Map<String,Object>> list =(List<Map<String,Object>>) params.get("goodsList");
        if(list!=null && list.size()>0){
            Integer allCount = list.size();
            Integer ableCount = 0;
            Integer unableCount = 0;
            for(Map<String,Object> goods : list){
                Integer count = 0;
                try {
                    Long goodsCount = 0L;
                    Long goodsSkuCount = 0L;
                    if(!StringUtils.isEmpty(goods.get("goodsCount"))){
                        goodsCount = Long.valueOf(goods.get("goodsCount").toString());
                    }
                    if((!StringUtils.isEmpty(goods.get("mallsAmountMin")) && !"0.00".equals(goods.get("mallsAmountMin").toString())) &&
                            (!StringUtils.isEmpty(goods.get("mallsAmountMax")) && !"0.00".equals(goods.get("mallsAmountMax").toString()))
                    ){
                        goods.remove("goodsCount");
                    }
                    try{
                        Map goodsNew = new HashMap();
                        goodsNew.put("goodsId",goods.get("goodsId"));
                        if(!StringUtils.isEmpty(goods.get("skuId")) && !goods.get("skuId").toString().startsWith("g") ){
                            goodsNew.put("skuId",goods.get("skuId"));
                        }
                        goodsNew.put("orgId",goods.get("orgId"));
                        goodsNew.put("adminId",goods.get("adminId"));
                        Map<String, Object> oldGoods =  shopGoodsMapper.getImportGoods(goodsNew);
                        oldGoods.put("moneyAmount",goods.get("moneyAmountEnd"));
                        //根据商品id获取优惠券列表
                        List<Map<String, Object>> couponList = isLossGoodsService.getCouponListByGoodsId(userinfo,Long.valueOf(goods.get("goodsId").toString()));
                        if(couponList.size()>0){
                            Map capyMap = new HashMap();
                            CopyMap.mapCopy(oldGoods,capyMap);
                            for (Map<String, Object> couponInfo : couponList){
                                //销售金额和会员价减去优惠金额
                                capyMap = isLossGoodsService.reduceGoodsInfoByMap(capyMap,couponInfo);
                                if(!StringUtils.isEmpty(capyMap.get("isFreeFreight")) && "1".equals(capyMap.get("isFreeFreight").toString())){
                                    capyMap.remove("isFreight");
                                }
                                newMallService.checkGoodsRewetting(capyMap);
                            }
                        }else {
                            newMallService.checkGoodsRewetting(oldGoods);
                        }
                        String memberAmountOldS = oldGoods.get("memberAmount").toString();
                        String mallsAmountMinS = oldGoods.get("mallsAmountMin").toString();
                        String mallsAmountMaxS = oldGoods.get("mallsAmountMax").toString();
                        String originalCostS = oldGoods.get("originalCost").toString();
                        Double moneyAmountEnd = Double.valueOf(goods.get("moneyAmountEnd").toString());
                        Double memberAmountOld = Double.valueOf(memberAmountOldS);
                        Double mallsAmountMin = Double.valueOf(mallsAmountMinS);
                        Double mallsAmountMax = Double.valueOf(mallsAmountMaxS);
                        Double originalCost = Double.valueOf(originalCostS);
                        if(moneyAmountEnd<=memberAmountOld || moneyAmountEnd<mallsAmountMin || (mallsAmountMax>0 && moneyAmountEnd>mallsAmountMax)
                                || (originalCost>0 && moneyAmountEnd>=originalCost)){
                            throw GlobalException.build("不符合");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        LOGGER.info("商品亏损，goodsId"+goods.get("goodsId"));
                        throw GlobalException.build("商品亏损");
                    }
                    Long goodsId = Long.valueOf(goods.get("goodsId").toString());
                    String skuId = null;
                    LOGGER.info("批量修改商品数据======="+JSON.toJSONString(goods));
                    //事务管理
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    TransactionStatus status = txManager.getTransaction(def);
                    if(!StringUtils.isEmpty(goods.get("skuId")) && goods.get("skuId").toString().startsWith("g")){
                        count = shopGoodsMapper.updateImportGoods(goods);
                    }else  if(!StringUtils.isEmpty(goods.get("skuId")) && !goods.get("skuId").toString().startsWith("g")){
                        count = shopGoodsMapper.updateImportGoodsSku(goods);
                        skuId = goods.get("skuId").toString();
                        if(count>0){
                            goodsCount = shopGoodsMapper.getImportGoodsCount(goods);
                            //修改商品总库存
                            count = shopGoodsMapper.updateImportGoodsCount(goods);
                        }
                    }
                    txManager.commit(status);
                    mallService.flushGoodsCache(true,goodsId,null,0L);
                    mallService.flushGoodsCache(false,goodsId,null,goodsCount);
                    if(skuId != null && goodsCount>0){
                        mallService.flushGoodsCache(false,goodsId,skuId,goodsSkuCount);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LOGGER.info("修改商品失败！，商品详情====="+JSON.toJSONString(goods));
                }
                if(count==1){
                    goods.put("status",1);
                    ableCount++;
                }else {
                    goods.put("status",0);
                    unableCount++;
                }
                goods.put("importId",importId);
                if(!goods.containsKey("goodsCount")){
                    goods.put("goodsCount",goods.get("goodsCountOld"));
                }
                shopGoodsMapper.insertImportGoods(goods);
            }
            params.put("allCount",allCount);
            params.put("ableCount",ableCount);
            params.put("unableCount",unableCount);
            shopGoodsMapper.insertImport(params);
        }

    }

    public List<Map<String, Object>> getImportList(Map<String, Object> params) {
        return shopGoodsMapper.getImportList(params);
    }

    public List<Map<String, Object>> getImportGoodsList(String importId,Integer status) {
        return shopGoodsMapper.getImportGoodsList(importId,status);
    }
}
